﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Vampirewal.Console.Core;
using Vampirewal.Core.ScheduledTask;

namespace Test.Console1;

public class Program
{
    private static Task Main(string[] args)
    {
        //await VampirewalConsoleCore.Run(RunOptions.Instance
        //                                           .WithArgs(args)
        //                                           .ConfigureBuilder(builder =>
        //                                           {
        //                                               builder.Host.UseWindowsService();


        //                                           })
        //                                           .ConfigureServices(services =>
        //                                           {
        //                                               services.AddVampirewalCoreScheduledTask(option =>
        //                                               {
        //                                                   option.Register<TestJob1>(job =>
        //                                                   {
        //                                                       job.JobName = "测试1";
        //                                                       job.JobDescription = "每10秒执行1次";
        //                                                       job.CronExpression = "*/10 * * * * ";
        //                                                       job.RetryCount = 3;
        //                                                   });

        //                                                   //option.Register<TestJob1>(job =>
        //                                                   //{
        //                                                   //    job.JobName = "测试2";
        //                                                   //    job.JobDescription = "每15秒执行1次";
        //                                                   //    job.CronExpression = "*/15 * * * * *";
        //                                                   //});
        //                                               });
        //                                           })
        //                                           .Configure(app =>
        //                                           {
        //                                               //var taskService= app.Services.GetRequiredService<IVampirewalCoreScheduledTaskService>();

        //                                               //taskService.Running();

        //                                               app.UseVampirewalCoreScheduledTask();

        //                                           })
        //                                           );

        Console.WriteLine("启动服务器...");

        while (true)
        {
            // 创建新的命名管道服务器实例等待客户端连接
            NamedPipeServerStream pipeServer = new NamedPipeServerStream("MyPipe", PipeDirection.InOut);
            Console.WriteLine("等待客户端连接...");
            pipeServer.WaitForConnection();
            Console.WriteLine("客户端已连接。");

            // 启动新线程来处理客户端通信
            Task.Run(() => HandleClient(pipeServer));
        }

    }

    static void HandleClient(NamedPipeServerStream pipeServer)
    {
        using (pipeServer)
        using (StreamReader reader = new StreamReader(pipeServer))
        using (StreamWriter writer = new StreamWriter(pipeServer))
        {
            writer.AutoFlush = true;

            // 处理客户端消息
            try
            {
                while (true)
                {
                    string line = reader.ReadLine();
                    if (line == null) break; // 断开连接
                    Console.WriteLine("从客户端接收到: " + line);

                    // 回复客户端
                    writer.WriteLine("服务器已收到: " + line);
                }
            }
            catch (IOException)
            {
                Console.WriteLine("客户端已断开连接。");
            }
        }
    }

    /// <summary>
    /// 获取方法执行时间
    /// </summary>
    /// <param name="action"></param>
    /// <returns><paramref name="毫秒数"/></returns>
    public static string GetMethodExcuteTime(Action action)
    {
        Stopwatch sw = new Stopwatch();
        sw.Start();
        action.Invoke();
        sw.Stop();

        return sw.ElapsedMilliseconds.ToString();
    }

    
}

public class TestJob1 : IJob
{
    public TestJob1(IServiceProvider service)
    {
        
    }


    public Task ExcuteAsync(JobContext context)
    {
        StringBuilder sb = new StringBuilder();

        sb.AppendLine($"--- {DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")} ---");

        sb.AppendLine($"任务名称：{context.JobName}");
        sb.AppendLine($"任务描述：{context.JobDescription}");
        sb.AppendLine($"任务已执行次数：{context.ExcuteCount}");

        sb.AppendLine("------");
        sb.AppendLine();

        Console.WriteLine(sb.ToString());

        throw new Exception("测试异常重试");

        return Task.CompletedTask;
    }

    public async Task OnExcuteErrorAsync(JobContext context, Exception ex)
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine(ex.Message);
        Console.ForegroundColor= ConsoleColor.White;
        await Task.CompletedTask;
    }
}